import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class BeijingshiConditionPolicy(BaseTaxPolicySpider):
    name = "beijingshi_condition_policy"

    province: str = '北京市'  # 取表格
    city: str = '北京市'  # 取表格
    county: str = ""  # 取表格
    park: str = "None"  # 取表格
    source: str = "北京市农业农村局"  # 取表格 同一个来源合并
    # url: str = "https://nyncj.beijing.gov.cn/nyj/zwgk/zcgk/zcwj3149/index.html"  # 注明入口网址，以便后续排错

    @classmethod
    def update_settings(cls, settings) -> None:
        downloader_middlewares = settings.getdict("DOWNLOADER_MIDDLEWARES")
        new_settings = {
            **(cls.custom_settings or {}),
            **{
                "DOWNLOADER_MIDDLEWARES": {
                    "components.middlewares.downloadmiddlewares.public.jsl_middlewares.JslMiddleware": 543,
                    **downloader_middlewares
                }
            },
        }
        settings.setdict(new_settings or {}, priority="spider")

    def start_requests(self):
        for source, county, url in [
            ['北京市农业农村局', '', "https://nyncj.beijing.gov.cn/nyj/zwgk/zcgk/zcwj3149/index.html"],
            ['北京市农业农村局', '', "https://nyncj.beijing.gov.cn/nyj/zwgk/zcgk/qtzcwj90/index.html"],
            ['北京市农业农村局', '', "https://nyncj.beijing.gov.cn/nyj/zwgk/zcgk/xzgfxwj12/index.html"],
            ['北京市知识产权局', '', 'https://zscqj.beijing.gov.cn/zscqj/zwgk/zcwj92/index.html'],
            ['北京市昌平区人民政府', '昌平区', 'https://www.bjchp.gov.cn/cpqzf/xxgk2671/zcwj/index.html'],
        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_response, meta={"item": item})

    def parse_response(self, response, **kwargs):
        url = response.xpath("//a[@title='下一页']/@onclick").re_first(r"""this,'(.*)'""")
        if not url:
            url = response.url
        # print(url)
        yield response.follow(url, callback=self.parse_list, dont_filter=True, meta=response.meta)

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        elem_list = response.xpath(
            "//*[@class='default_news' or @class='list' or @class='ul-back' or @class='subpageCon-conList']//li//a[(contains(@href, 'htm') or @title) and not(starts-with(text(), '|'))]/ancestor::li[string-length(string(.))>=9] |"
            "//*[@class='fl zclist' or @class='listNews' or @class='sxwjBox']//li//a[(contains(@href, 'htm') or @title) and not(starts-with(text(), '|'))]/ancestor::li[string-length(string(.))>=9]"
            "")
        print(len(elem_list), response.url)
        for elem in elem_list:
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").re_first(r"""(.*/.*)""")
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if '.htm' not in item['source_url'] and '.shtm' not in item['source_url']:
                continue
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            total_page = int(response.xpath(""".""").re_first(r'totalpage="(\d+)"'))
            # if total_page > 5 and '/eportal/ui' in response.text:
            #     new_url = response.xpath(""".""").re_first(r"""queryArticleByCondition\(this,'(.*)'""")
            for page_num in range(1, total_page + 1):
                url = re.sub(r"-(\d+)?\.", r"-{}.".format(page_num), response.url)
                print(url)
                yield response.follow(url, callback=self.parse_list, meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get().split(' ')[0]
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        # item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl beijingshi_condition_policy".split())
